package internal

import (
	"bytes"
	"fmt"
	"github.com/BurntSushi/toml"
	"github.com/jinzhu/now"
	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
	"github.com/robfig/cron/v3"
	"go.uber.org/zap"
	"log"
	"os"
	"zt-compute/config"
)

func Init(configPath string) {
	_, err := toml.DecodeFile(configPath, &config.MyConfig)
	if err != nil {
		log.Fatal(err)
	}
	initLogConfig()

	config.MyConfig.FastDBAddress = fmt.Sprintf("http://%s:%d", config.MyConfig.FastDBIp, config.MyConfig.FastDBPort)
	var firstBuffer bytes.Buffer
	e := toml.NewEncoder(&firstBuffer)
	_ = e.Encode(config.MyConfig)
	connectionString := fmt.Sprintf(
		"host=%s port=%d user=%s "+
			"password=%s dbname=%s sslmode=disable", config.MyConfig.DBIp, config.MyConfig.DBPort, config.MyConfig.DBUName,
		config.MyConfig.DBPwd, config.MyConfig.DBName)
	MyLog.Info("数据库链接", zap.String("connectionString", connectionString))
	config.MyConfig.SqlEngine, err = sqlx.Connect("postgres", connectionString)
	if err != nil {
		MyLog.Fatal("连接数据库失败:", err)
	}
	err = config.MyConfig.SqlEngine.Ping()
	if err != nil {
		MyLog.Fatal("连接数据库失败:", err)
	}
}

func InitJob() {
	if len(config.MyConfig.CalcJobs) > 0 {
		c := cron.New()
		for _, job := range config.MyConfig.CalcJobs {
			beginTime, err := now.Parse(job.BeginTime)
			if err != nil {
				MyLog.Fatal("计算开始时间解析失败:", err)
			}
			endTime, err := now.Parse(job.EndTime)
			if err != nil {
				MyLog.Fatal("计算结束时间解析失败:", err)
			}
			SaveData(beginTime, endTime)
			_, err = c.AddFunc(job.TriggerTime, func() {
				SaveData(beginTime, endTime)
			})
			if err != nil {
				MyLog.Error(err)
			}
		}
		c.Start()
	} else {
		MyLog.Warn("没有配置计算任务，程序退出")
		os.Exit(0)
	}
}
